#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <errno.h>
#include <sys/mman.h>
#include <linux/videodev2.h>
#include <linux/fb.h>

#define FB_DEV "/dev/fb0" //LCD 设备节点
#define FRAMEBUFFER_COUNT 10 //帧缓冲数量
#define RGB565(r, g, b) (((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3))

void YUYV_to_RGB565(unsigned char *yuyv_data, unsigned short *rgb565_buffer,
                    int width, int height,unsigned int length);
/*** 摄像头像素格式及其描述信息 ***/
typedef struct camera_format {
 unsigned char description[32]; //字符串描述信息
 unsigned int pixelformat; //像素格式
} cam_fmt;

/*** 描述一个帧缓冲的信息 ***/
typedef struct cam_buf_info {
 unsigned short *start; //帧缓冲起始地址
 unsigned long length; //帧缓冲长度
} cam_buf_info;

static int width;   //LCD宽度
static int height; //LCD高度
static unsigned short* screen_base = NULL;//显存的基地址
static int fb_fd = -1; //LCD 设备文件描述符
static int v4l2_fd = -1; //摄像头设备文件描述符

static cam_buf_info buf_infos[FRAMEBUFFER_COUNT];
static cam_fmt cam_fmts[10];
static int frm_width,frm_height; //视频帧的宽度和高度

static int fb_dev_init(void)
{
    struct fb_var_screeninfo fb_var = {0};
    struct fb_fix_screeninfo fb_fix = {0};
    unsigned long screen_size;

    fb_fd = open(FB_DEV,O_RDWR);
    if (0 > fb_fd) {
        fprintf(stderr, "open error: %s: %s\n", FB_DEV, strerror(errno));
        return -1;
    }
    // 获取信息设定参数
    ioctl(fb_fd,FBIOGET_VSCREENINFO,&fb_var);
    ioctl(fb_fd,FBIOGET_FSCREENINFO,&fb_fix);

    screen_size = fb_fix.line_length * fb_var.yres;
    width = fb_var.xres;
    height = fb_var.yres;

    //内存映射
    screen_base = mmap(NULL, screen_size, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd, 0);
    if (MAP_FAILED == (void *)screen_base) {
        perror("mmap error");
        close(fb_fd);
        return -1;
    }
    /* LCD 背景刷白 */
    memset(screen_base, 0xFF, screen_size);
    return 0;
}

// 设备初始化
static int v4l2_dev_init(const char* device)
{
    struct v4l2_capability cap = {0};
    /* 打开摄像头 */
    v4l2_fd = open(device, O_RDWR);
    if (0 > v4l2_fd) {
        fprintf(stderr, "open error: %s: %s\n", device, strerror(errno));
        return -1;
    }
    /* 查询设备功能 */
    ioctl(v4l2_fd, VIDIOC_QUERYCAP, &cap);
    /* 判断是否是视频采集设备 */
    if (!(V4L2_CAP_VIDEO_CAPTURE & cap.capabilities)) {
        fprintf(stderr, "Error: %s: No capture video device!\n", device);
        close(v4l2_fd);
        return -1;
    }
    return 0;
}

//列举所有支持的像素格式
// 假如说最大不超过10种把
static void v4l2_enum_format(void)
{
    struct v4l2_fmtdesc fmtdesc = {0};
    /* 枚举摄像头所支持的所有像素格式以及描述信息 */
    fmtdesc.index = 0;
    fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    // 从第0个依次列举
    while(0 == ioctl(v4l2_fd,VIDIOC_ENUM_FMT, &fmtdesc)) {
        cam_fmts[fmtdesc.index].pixelformat = fmtdesc.pixelformat;
        strcpy(cam_fmts[fmtdesc.index].description, fmtdesc.description);
        fmtdesc.index++;
    }
}

//打印所有的参数 包括pixel_format 分辨率  帧数

static void v4l2_print_format(void)
{
    struct v4l2_frmsizeenum frmsize = {0};
    struct v4l2_frmivalenum frmival = {0};
    int i;
    // 先设定好type
    frmsize.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    frmival.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
   for (i = 0; cam_fmts[i].pixelformat; i++) {
        // 某种格式
        printf("format<0x%x>, description<%s>\n", cam_fmts[i].pixelformat,
            cam_fmts[i].description);
        /* 枚举出摄像头所支持的所有视频采集分辨率 */
        frmsize.index = 0;
        frmsize.pixel_format = cam_fmts[i].pixelformat;
        frmival.pixel_format = cam_fmts[i].pixelformat;
        
        while (0 == ioctl(v4l2_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize)) {
            printf("size<%d*%d> ",
            frmsize.discrete.width,
            frmsize.discrete.height);
            frmsize.index++;

            // 所支持的帧率
            frmival.index = 0;
            frmival.width = frmsize.discrete.width;
            frmival.height = frmsize.discrete.height;

            while (0 == ioctl(v4l2_fd, VIDIOC_ENUM_FRAMEINTERVALS, &frmival)) {
                printf("<%dfps>", frmival.discrete.denominator / frmival.discrete.numerator);
                frmival.index++;
            }
            printf("\n");
        }
        printf("\n");
        
    }
}

static int v4l2_set_format(void)
{
    struct v4l2_format fmt = {0};
    struct v4l2_streamparm streamparm = {0};

    /* 设置帧格式 */
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;//type 类型
    fmt.fmt.pix.width = 640; //视频帧宽度 等于屏幕高度?
    fmt.fmt.pix.height = 480;//视频帧高度
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB565; //像素格式

    // 设置完之后坑不会都按照自己想的来
    // 所以可以看看fmt 有没有被改 或者被改成啥了
    if (0 > ioctl(v4l2_fd, VIDIOC_S_FMT, &fmt)) {
        fprintf(stderr, "ioctl error: VIDIOC_S_FMT: %s\n", strerror(errno));
        return -1;
    }

     /*** 判断是否已经设置为我们要求的 RGB565 像素格式
     如果没有设置成功表示该设备不支持 RGB565 像素格式 */

    frm_width = fmt.fmt.pix.width; //获取实际的帧宽度
    frm_height = fmt.fmt.pix.height;//获取实际的帧高度
    printf("视频帧大小<%d * %d>\n", frm_width, frm_height);

    /* 获取 streamparm */
    // 主要是看看支不支持设置视频的帧率
    streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ioctl(v4l2_fd, VIDIOC_G_PARM, &streamparm);
    
    if (V4L2_CAP_TIMEPERFRAME & streamparm.parm.capture.capability) {
        streamparm.parm.capture.timeperframe.numerator = 1;
        streamparm.parm.capture.timeperframe.denominator = 30;//30fps
        if (0 > ioctl(v4l2_fd, VIDIOC_S_PARM, &streamparm)) {
            fprintf(stderr, "ioctl error: VIDIOC_S_PARM: %s\n", strerror(errno));
            return -1;
        }
    }
    return 0;
}



static int v4l2_init_buffer(void)
{
    struct v4l2_requestbuffers reqbuf = {0};
    struct v4l2_buffer buf = {0};

    /* 申请帧缓冲 */
    reqbuf.count = FRAMEBUFFER_COUNT; //帧缓冲的数量
    reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    reqbuf.memory = V4L2_MEMORY_MMAP;
    if (0 > ioctl(v4l2_fd, VIDIOC_REQBUFS, &reqbuf)) {
        fprintf(stderr, "ioctl error: VIDIOC_REQBUFS: %s\n", strerror(errno));
        return -1;
    }

    // 建立内存映射
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    for (buf.index = 0; buf.index < FRAMEBUFFER_COUNT; buf.index++) {
        ioctl(v4l2_fd, VIDIOC_QUERYBUF, &buf);
        buf_infos[buf.index].length = buf.length;
        buf_infos[buf.index].start = mmap(NULL, buf.length,
                        PROT_READ | PROT_WRITE, MAP_SHARED,v4l2_fd, buf.m.offset);
        if (MAP_FAILED == buf_infos[buf.index].start) {
            perror("mmap error");
            return -1;
        }
    }

    /* 入队操作 */
    for (buf.index = 0; buf.index < FRAMEBUFFER_COUNT; buf.index++) {
        if (0 > ioctl(v4l2_fd, VIDIOC_QBUF, &buf)) {
            fprintf(stderr, "ioctl error: VIDIOC_QBUF: %s\n", strerror(errno));
            return -1;
        }
    }
    return 0;
}

// 开启视频流
static int v4l2_stream_on(void)
{
    /* 打开摄像头、摄像头开始采集数据 */
    // 枚举类型等于类型
    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (0 > ioctl(v4l2_fd, VIDIOC_STREAMON, &type)) {
        fprintf(stderr, "ioctl error: VIDIOC_STREAMON: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

//读取数据
static void v4l2_read_data(void)
{
    struct v4l2_buffer buf = {0};
    unsigned short *base;
    unsigned short *start;
    int min_w,min_h;
    int j;
    if(width > frm_width)
        min_w = frm_width;
    else
        min_w = width;
    if (height > frm_height)
        min_h = frm_height;
    else
        min_h = height;
    
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;

    for(;;) {
        for(buf.index = 0; buf.index <FRAMEBUFFER_COUNT;buf.index++)
        {
            ioctl(v4l2_fd,VIDIOC_DQBUF,&buf);

            // Convert YUYV to RGB565 and store in screen_base
            // 其实这个也是两个字节两个字节读取的
        
            YUYV_to_RGB565((unsigned char *)buf_infos[buf.index].start, screen_base, min_w, min_h,buf.length);
            // 数据处理完之后、再入队、往复
            // 及时出队
            ioctl(v4l2_fd, VIDIOC_QBUF, &buf);
        }
    }
}
// 一帧图像的长度
void YUYV_to_RGB565(unsigned char *yuyv_data, unsigned short *rgb565_buffer, 
                    int min_w, int min_h,unsigned int length) {
    int i, j;
    int y0, u, y1, v;
    int r, g, b;
    unsigned int count = 0;
    unsigned int h = 0;
    //YUYV 是用4个字节描述两个像素
    //而RGB565呢 则是一个像素用了两个字节
    for (i = 0; i < length; i = i + 4) {
        // Extract YUV components from YUYV format
        y0 = yuyv_data[i];
        u = yuyv_data[i + 1] - 128;
        y1 = yuyv_data[i + 2];
        v = yuyv_data[i + 3] - 128;

        // Convert YUV to RGB
        // Convert YUV to RGB for first pixel using integer math
        r = y0 + ((v * 1436) >> 10); // 1.402 * 1024 = 1436
        g = y0 - ((u * 352) >> 10) - ((v * 731) >> 10); // 0.344136 * 1024 = 352, 0.714136 * 1024 = 731
        b = y0 + ((u * 1815) >> 10); // 1.772 * 1024 = 1815
        // Clamp RGB values
        r = (r > 255) ? 255 : (r < 0) ? 0 : r;
        g = (g > 255) ? 255 : (g < 0) ? 0 : g;
        b = (b > 255) ? 255 : (b < 0) ? 0 : b;
        // Pack RGB565 format
        unsigned short rgb565_pixel = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
        // 理论上来说是这样但实际要考虑width 和height
        // 一次性会增加两个字节
        //*(rgb565_buffer ++ ) = rgb565_pixel;
        rgb565_buffer[h * width + count] = rgb565_pixel;
        count++;
        // Process next YUV pair
        y0 = y1;
        // Convert YUV to RGB
        r = y0 + ((v * 1436) >> 10); // 1.402 * 1024 = 1436
        g = y0 - ((u * 352) >> 10) - ((v * 731) >> 10); // 0.344136 * 1024 = 352, 0.714136 * 1024 = 731
        b = y0 + ((u * 1815) >> 10); // 1.772 * 1024 = 1815
        // Clamp RGB values
        r = (r > 255) ? 255 : (r < 0) ? 0 : r;
        g = (g > 255) ? 255 : (g < 0) ? 0 : g;
        b = (b > 255) ? 255 : (b < 0) ? 0 : b;
        // Pack RGB565 format for second pixel
        rgb565_pixel = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);

        // 一次性会增加两个字节
        //*(rgb565_buffer ++ ) = rgb565_pixel;
        rgb565_buffer[h * width + count] = rgb565_pixel;
        count++;
        if(count == min_w) {
            count = 0;
            h++;
            if(h == min_h)
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    if (2 != argc) {
        fprintf(stderr, "Usage: %s <video_dev>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    /* 初始化 LCD */
    if (fb_dev_init())
        exit(EXIT_FAILURE);
    /* 初始化摄像头 */
    if (v4l2_dev_init(argv[1]))
        exit(EXIT_FAILURE);
    /* 枚举所有格式并打印摄像头支持的分辨率及帧率 */
    v4l2_enum_format();
    v4l2_print_format();
    /* 设置格式 */
    if (v4l2_set_format())
        exit(EXIT_FAILURE);
    if (v4l2_init_buffer())
        exit(EXIT_FAILURE);
    /* 开启视频采集 */
    if (v4l2_stream_on())
        exit(EXIT_FAILURE);
    /* 读取数据：出队 */
    v4l2_read_data(); //在函数内循环采集数据、将其显示到 LCD 屏
    exit(EXIT_SUCCESS);
}